﻿package com.thorqq.magictimer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.baidu.mobstat.StatService;
import com.thorqq.magictimer.action.ActionSendSMS;
import com.thorqq.magictimer.timeLoop.TimerMgr;
import com.thorqq.magictimer.util.Util;
import com.thorqq.magictimer.widget.QuickAlphabeticBar;

public class SelectContactsActivity extends Activity
{

    private SelectContactsAdapter adapter;
    private ListView personList;

    private List<ContactBean> list;
    private AsyncQueryHandler asyncQuery;
    private QuickAlphabeticBar alpha;

    private List<ContactBean> selectContactList = new ArrayList<ContactBean>();
    private Button returnBtn;
    private Button doneBtn;
    private Map<String, String> selectMap = new HashMap<String, String>();
    
    private ActionSendSMS mAction;
    private int mContactSize = -1;

    public void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.select_contacts_to_send);
        
        //收到的参数action
        mAction = (ActionSendSMS)getIntent().getExtras().getSerializable(TimerMgr.ALARM_INTENT_ACTION);
        if(mAction == null)
        {
            Util.log("error action");
        }
        selectMap.clear();
        selectMap.putAll(mAction.getPhoneNumber());
        
        //限制只能选择几个联系人（发短信可多选，打电话只能单选）
        mContactSize = getIntent().getIntExtra(TimerMgr.ALARM_INTENT_EXTRA, -1);

        personList = (ListView) findViewById(R.id.list);

        alpha = (QuickAlphabeticBar) findViewById(R.id.fast_scroller);
        asyncQuery = new MyAsyncQueryHandler(getContentResolver());
        init();

        returnBtn = (Button) findViewById(R.id.btn_contact_return);
        doneBtn = (Button) findViewById(R.id.btn_done);

        //返回键
        returnBtn.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {
                SelectContactsActivity.this.finish();
            }
        });
        
        //确定键
        doneBtn.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {
                mAction.setPhoneNumber(selectMap);

                Intent i = new Intent();
                i.putExtra(TimerMgr.ALARM_INTENT_ACTION, mAction);
                setResult(RESULT_OK, i);
                finish();
            }
        });

        setDoneBtnText();
    }
    
    @Override
    public void onResume()
    {
        super.onResume();

        /**
         * 此处调用基本统计代码
         */
        StatService.onResume(this);
    }

    @Override
    public void onPause()
    {
        super.onPause();

        /**
         * 此处调用基本统计代码
         */
        StatService.onPause(this);
    }

    private void setDoneBtnText()
    {
        int cnt = selectMap.size();
        if(cnt > 0)
        {
            doneBtn.setText(getString(R.string.btn_save) + "(" + selectMap.size() + ")");
        }
        else
        {
            doneBtn.setText(getString(R.string.btn_save));
        }

    }

    //查询通讯录
    private void init()
    {
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; // 联系人的Uri
        String[] projection = { ContactsContract.CommonDataKinds.Phone._ID,
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.DATA1, "sort_key",
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
                ContactsContract.CommonDataKinds.Phone.PHOTO_ID,
                ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY }; // 查询的列
        asyncQuery.startQuery(0, null, uri, projection, null, null,
                "sort_key COLLATE LOCALIZED asc"); // 按照sort_key升序查询
    }

    private class MyAsyncQueryHandler extends AsyncQueryHandler
    {

        public MyAsyncQueryHandler(ContentResolver cr)
        {
            super(cr);
        }

        /**
         * 查询结束的回调函数
         */
        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor)
        {
            if (cursor != null && cursor.getCount() > 0)
            {

                list = new ArrayList<ContactBean>();
                cursor.moveToFirst();
                for (int i = 0; i < cursor.getCount(); i++)
                {
                    cursor.moveToPosition(i);
                    String name = cursor.getString(1);
                    String number = cursor.getString(2);
                    String sortKey = cursor.getString(3);
                    int contactId = cursor.getInt(4);
                    Long photoId = cursor.getLong(5);
                    String lookUpKey = cursor.getString(6);

                    ContactBean cb = new ContactBean();
                    cb.setDisplayName(name);
                    // if (number.startsWith("+86")) {//
                    // 去除多余的中国地区号码标志，对这个程序没有影响??
                    // cb.setPhoneNum(number.substring(3));
                    // } else {
                    cb.setPhoneNum(number);
                    // }
                    cb.setSortKey(sortKey);
                    cb.setContactId(contactId);
                    cb.setPhotoId(photoId);
                    cb.setLookUpKey(lookUpKey);

                    if (null == selectMap)
                    {
                    } else
                    {
                        if (selectMap.containsKey(number))
                        {
                            cb.setSelected(1);
                        }
                    }

                    list.add(cb);

                }
                if (list.size() > 0)
                {
                    setAdapter(list);
                }
            }
        }

    }

    private void setAdapter(List<ContactBean> list)
    {
        adapter = new SelectContactsAdapter(this, list, alpha);
        personList.setAdapter(adapter);
        alpha.init(SelectContactsActivity.this, R.id.fast_position);
        alpha.setListView(personList);
        alpha.setHight(alpha.getHeight());
        alpha.setVisibility(View.VISIBLE);
        personList.setOnItemClickListener(new OnItemClickListener()
        {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                ContactBean cb = (ContactBean) adapter.getItem(position);
                boolean check = SelectContactsAdapter.isSelected.get(position);
                if (check)
                {
                    SelectContactsAdapter.isSelected.put(position, false);
                    selectContactList.remove(cb);
                    selectMap.remove(cb.getPhoneNum());
                } else
                {
                    SelectContactsAdapter.isSelected.put(position, true);
                    //如果只能选取一个号码
                    if(mContactSize == 1)
                    {
                        for(Integer key: SelectContactsAdapter.isSelected.keySet())
                        {
                            if(!key.equals(position))
                            {
                                SelectContactsAdapter.isSelected.put(key, false);
                            }
                        }
                        
                        selectContactList.clear();
                        selectMap.clear();
                    }
                    selectContactList.add(cb);
                    selectMap.put(cb.getPhoneNum(), cb.getDisplayName());
                }
                
                setDoneBtnText();
                adapter.notifyDataSetChanged();
            }
        });
    }

}
